<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
        <span v-if="item.redirect === 'noRedirect' || index === levelList.length - 1" class="no-redirect">
          {{ getBreadcrumbTitle(item) }}
        </span>
        <a v-else @click.prevent="handleLink(item)">
          {{ getBreadcrumbTitle(item) }}
        </a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script setup>
import {ref, watchEffect} from 'vue'
import {useRoute, useRouter} from 'vue-router'

const route = useRoute()
const router = useRouter()
const levelList = ref([])

// 获取面包屑标题（使用动态设置的 meta.title）
function getBreadcrumbTitle(item) {
  // 直接使用 meta.title，不再需要特殊处理
  return item.meta?.title || item.name || ''
}

function getBreadcrumb() {
  // 只显示有 meta.title 的路由
  let matched = route.matched.filter(item => item.meta && item.meta.title)

  // 移除对 newsDetail 的特殊处理 - 这是问题的关键
  // 不再需要以下代码：
  /*
  const newsDetailRoute = matched.find(item => item.name === 'newsDetail')
  if (newsDetailRoute) {
    newsDetailRoute.meta.title = route.params.type === '-1'
        ? '新闻动态发布'
        : '新闻动态编辑'
  }
  */

  const first = matched[0]
  // 判断是否为首页
  if (!isDashboard(first)) {
    matched = [{path: '/index', meta: {title: '首页'}}].concat(matched)
  }

  levelList.value = matched.filter(
      item => item.meta && item.meta.title && item.meta.breadcrumb !== false
  )
  console.log(levelList.value,'levelList.value')
}

function isDashboard(route) {
  const name = route && route.name
  if (!name) {
    return false
  }
  return name.trim().toLowerCase() === 'index'
}

function handleLink(item) {
  const {redirect, path} = item
  if (redirect) {
    router.push(redirect)
    return
  }
  router.push(path)
}

watchEffect(() => {
  // 如果是重定向页面，不更新面包屑
  if (route.path.startsWith('/redirect/')) {
    return
  }
  getBreadcrumb()
})

getBreadcrumb()
</script>

<style lang='scss' scoped>
.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}

/* 面包屑过渡效果 */
.breadcrumb-enter-active,
.breadcrumb-leave-active {
  transition: all 0.5s;
}

.breadcrumb-enter-from,
.breadcrumb-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

.breadcrumb-leave-active {
  position: absolute;
}
</style>